/********************************************************
 * Filename: TclNamespaceLabelProvider.java
 * Author: LMU
 * Program: TUnit
 * Description: Updates the Namespace Explorer with the 
 * proper labels and icons for namespaces and procedures.  
 * Revision History:
 * 20060904: Initial revision.  Added header later.  
 * *****************************************************/

package edu.lmu.cs.tUnit.view.treeviewer;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.net.URL;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;

import edu.lmu.cs.tUnit.plugin.TUnitPlugin;
import edu.lmu.cs.tUnit.view.model.TclNamespace;
import edu.lmu.cs.tUnit.view.model.TclProcedure;

public class TclNamespaceLabelProvider extends LabelProvider {	
	private Map imageCache = new HashMap(11);
	
	/*
	 * @see ILabelProvider#getImage(Object)
	 */
	public Image getImage(Object element) {
		ImageDescriptor descriptor = null;
		URL SAMPLE = null;
		if (element instanceof TclNamespace) {
			SAMPLE = TUnitPlugin.getDefault().getBundle().getEntry("/icons/namespace.gif");
			descriptor = ImageDescriptor.createFromURL(SAMPLE);
		} else if (element instanceof TclProcedure) {
			SAMPLE = TUnitPlugin.getDefault().getBundle().getEntry("/icons/procedure.gif");
			descriptor = ImageDescriptor.createFromURL(SAMPLE);
		} else {
			throw unknownElement(element);
		}

		//obtain the cached image corresponding to the descriptor
		Image image = (Image)imageCache.get(descriptor);
		if (image == null) {
			image = descriptor.createImage();
			imageCache.put(descriptor, image);
		}
		return image;
	}

	/*
	 * @see ILabelProvider#getText(Object)
	 */
	public String getText(Object element) {
		if (element instanceof TclNamespace) {
			if(((TclNamespace)element).getName() == null) {
				return "TclNamespace";
			} else {
				return ((TclNamespace)element).getName();
			}
		} else if (element instanceof TclProcedure) {
			return ((TclProcedure)element).getName();
		} else {
			throw unknownElement(element);
		}
	}

	public void dispose() {
		for (Iterator i = imageCache.values().iterator(); i.hasNext();) {
			((Image) i.next()).dispose();
		}
		imageCache.clear();
	}

	protected RuntimeException unknownElement(Object element) {
		return new RuntimeException("Unknown type of element in tree of type " + element.getClass().getName());
	}

}
